﻿(function () {

    window.Crucible = window.Crucible || {};
    var Crucible = window.Crucible;

    Crucible.ParticleCanvas = function (canvas, width, height) {
        this.canvas = canvas;
        canvas.width = width;
        canvas.height = height;
        this.ctx = canvas.getContext('2d');
    };

    Crucible.ParticleCanvas.prototype = function () {
        var Particle = function (x, y, vx, vy, w, h) {
            this.x = x;
            this.y = y;
            this.vx = vx;
            this.vy = vy;
            this.w = w;
            this.h = h;
        },

        particles = [],

        requestAnimationFrame =
            window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            (function (f) { window.setTimeout(f, 0); }),


        farOutsideCanvas = function (p, canvas) {
            return (p.x < -1000 || p.y < -1000 || p.x > canvas.width + 1000 || p.y > canvas.height + 1000);
        },

        draw = function () {
            var canvas = this.canvas;
            var cw = canvas.width;
            var ctx = this.ctx;

            ctx.globalCompositeOperation = "destination-out";
            ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            ctx.globalCompositeOperation = "source-over";
            ctx.fillStyle = 'gray';

            for (var i = 0; i < particles.length; i++) {
                var p = particles[i];
                ctx.fillRect(p.x, p.y, p.w, p.h);

                p.x += p.vx;
                p.y += p.vy;

                if (farOutsideCanvas(p, canvas)) {
                    particles.splice(i, 1);
                    i--;
                }
            }

            if (particles.length) {
                var self = this;
                requestAnimationFrame(function () { draw.apply(self); }, this.canvas);
            }

        },

        startAmbient = function (numParticles) {
            var maxSpeed = 130;
            for (var i = 0; i < numParticles; i++) {
                particles.push(
                    new Particle(
                        0,
                        Math.random() * this.canvas.height,
                        (Math.random() + 3) * maxSpeed / 4,
                        0,
                        maxSpeed,
                        4
                    )
                );
            }

            var self = this;
            requestAnimationFrame(function () { draw.apply(self); }, this.canvas);
        };

        return {
            startAmbient: startAmbient
        };

    }();


}());